{% extends 'base.html' %}
{% load static %}

{% block title %}系统管理仪表板 - 固定资产管理系统{% endblock %}

{% block extra_css %}
<style>
    .system-card {
        background: white;
        border-radius: 10px;
        padding: 20px;
        margin-bottom: 20px;
        box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        transition: transform 0.3s ease;
    }
    
    .system-card:hover {
        transform: translateY(-2px);
    }
    
    .health-score {
        font-size: 3rem;
        font-weight: bold;
        text-align: center;
        margin-bottom: 10px;
    }
    
    .health-score.excellent {
        color: #28a745;
    }
    
    .health-score.good {
        color: #17a2b8;
    }
    
    .health-score.fair {
        color: #ffc107;
    }
    
    .health-score.poor {
        color: #fd7e14;
    }
    
    .health-score.critical {
        color: #dc3545;
    }
    
    .metric-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 10px 0;
        border-bottom: 1px solid #eee;
    }
    
    .metric-item:last-child {
        border-bottom: none;
    }
    
    .metric-label {
        font-weight: 500;
        color: #666;
    }
    
    .metric-value {
        font-weight: bold;
        color: #333;
    }
    
    .progress-custom {
        height: 8px;
        border-radius: 4px;
        background-color: #e9ecef;
        overflow: hidden;
    }
    
    .progress-bar-custom {
        height: 100%;
        border-radius: 4px;
        transition: width 0.3s ease;
    }
    
    .progress-bar-success {
        background: linear-gradient(90deg, #28a745, #20c997);
    }
    
    .progress-bar-warning {
        background: linear-gradient(90deg, #ffc107, #fd7e14);
    }
    
    .progress-bar-danger {
        background: linear-gradient(90deg, #dc3545, #e83e8c);
    }
    
    .log-item {
        padding: 10px 15px;
        border-left: 4px solid #dee2e6;
        margin-bottom: 10px;
        background: #f8f9fa;
        border-radius: 0 5px 5px 0;
    }
    
    .log-item.error {
        border-left-color: #dc3545;
        background: #f8d7da;
    }
    
    .log-item.warning {
        border-left-color: #ffc107;
        background: #fff3cd;
    }
    
    .log-item.info {
        border-left-color: #17a2b8;
        background: #d1ecf1;
    }
    
    .status-indicator {
        display: inline-block;
        width: 12px;
        height: 12px;
        border-radius: 50%;
        margin-right: 8px;
    }
    
    .status-online {
        background-color: #28a745;
        animation: pulse 2s infinite;
    }
    
    .status-warning {
        background-color: #ffc107;
    }
    
    .status-offline {
        background-color: #dc3545;
    }
    
    @keyframes pulse {
        0% {
            box-shadow: 0 0 0 0 rgba(40, 167, 69, 0.7);
        }
        70% {
            box-shadow: 0 0 0 10px rgba(40, 167, 69, 0);
        }
        100% {
            box-shadow: 0 0 0 0 rgba(40, 167, 69, 0);
        }
    }
    
    .quick-action-btn {
        width: 100%;
        margin-bottom: 10px;
        border-radius: 8px;
        padding: 12px;
        font-weight: 500;
    }
    
    .storage-chart {
        position: relative;
        height: 200px;
    }
    
    .database-table {
        max-height: 300px;
        overflow-y: auto;
    }
    
    .refresh-indicator {
        display: none;
        color: #28a745;
        margin-left: 10px;
    }
</style>
{% endblock %}

{% block content %}
<div class="container-fluid">
    <!-- 页面标题 -->
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h2>
            <i class="fas fa-tachometer-alt"></i> 系统管理仪表板
            <span class="refresh-indicator" id="refreshIndicator">
                <i class="fas fa-sync-alt fa-spin"></i>
            </span>
        </h2>
        <div class="btn-group">
            <button class="btn btn-outline-primary" onclick="refreshDashboard()">
                <i class="fas fa-sync-alt"></i> 刷新数据
            </button>
            <button class="btn btn-outline-info" onclick="viewPerformanceMonitor()">
                <i class="fas fa-chart-line"></i> 性能监控
            </button>
            <button class="btn btn-outline-warning" onclick="viewSystemMaintenance()">
                <i class="fas fa-tools"></i> 系统维护
            </button>
        </div>
    </div>
    
    <!-- 系统健康状态 -->
    <div class="row">
        <div class="col-md-3">
            <div class="system-card text-center">
                <h5 class="mb-3">系统健康评分</h5>
                <div class="health-score {{ health_status.status }}">
                    {{ health_status.health_score|default:0 }}
                </div>
                <div class="text-muted">
                    {% if health_status.status == 'excellent' %}
                        <i class="fas fa-check-circle text-success"></i> 优秀
                    {% elif health_status.status == 'good' %}
                        <i class="fas fa-thumbs-up text-info"></i> 良好
                    {% elif health_status.status == 'fair' %}
                        <i class="fas fa-exclamation-triangle text-warning"></i> 一般
                    {% elif health_status.status == 'poor' %}
                        <i class="fas fa-exclamation-circle text-warning"></i> 较差
                    {% elif health_status.status == 'critical' %}
                        <i class="fas fa-times-circle text-danger"></i> 严重
                    {% else %}
                        <i class="fas fa-question-circle text-muted"></i> 未知
                    {% endif %}
                </div>
                <small class="text-muted">
                    运行时间: {{ health_status.uptime_days|default:0 }}天 {{ health_status.uptime_hours|default:0 }}小时
                </small>
            </div>
        </div>
        
        <div class="col-md-3">
            <div class="system-card">
                <h5 class="mb-3">CPU使用率</h5>
                <div class="metric-item">
                    <span class="metric-label">当前使用率</span>
                    <span class="metric-value">{{ health_status.cpu_percent|default:0 }}%</span>
                </div>
                <div class="progress-custom mt-2">
                    <div class="progress-bar-custom {% if health_status.cpu_percent > 80 %}progress-bar-danger{% elif health_status.cpu_percent > 60 %}progress-bar-warning{% else %}progress-bar-success{% endif %}" 
                         style="width: {{ health_status.cpu_percent|default:0 }}%"></div>
                </div>
                <div class="metric-item mt-3">
                    <span class="metric-label">系统负载</span>
                    <span class="metric-value">{{ health_status.load_avg.0|floatformat:2 }}</span>
                </div>
                <div class="metric-item">
                    <span class="metric-label">进程数</span>
                    <span class="metric-value">{{ health_status.process_count|default:0 }}</span>
                </div>
            </div>
        </div>
        
        <div class="col-md-3">
            <div class="system-card">
                <h5 class="mb-3">内存使用情况</h5>
                <div class="metric-item">
                    <span class="metric-label">使用率</span>
                    <span class="metric-value">{{ health_status.memory_percent|default:0 }}%</span>
                </div>
                <div class="progress-custom mt-2">
                    <div class="progress-bar-custom {% if health_status.memory_percent > 85 %}progress-bar-danger{% elif health_status.memory_percent > 70 %}progress-bar-warning{% else %}progress-bar-success{% endif %}" 
                         style="width: {{ health_status.memory_percent|default:0 }}%"></div>
                </div>
                <div class="metric-item mt-3">
                    <span class="metric-label">已用内存</span>
                    <span class="metric-value">{{ health_status.memory_used|default:0 }} GB</span>
                </div>
                <div class="metric-item">
                    <span class="metric-label">总内存</span>
                    <span class="metric-value">{{ health_status.memory_total|default:0 }} GB</span>
                </div>
            </div>
        </div>
        
        <div class="col-md-3">
            <div class="system-card">
                <h5 class="mb-3">磁盘使用情况</h5>
                <div class="metric-item">
                    <span class="metric-label">使用率</span>
                    <span class="metric-value">{{ health_status.disk_percent|default:0 }}%</span>
                </div>
                <div class="progress-custom mt-2">
                    <div class="progress-bar-custom {% if health_status.disk_percent > 85 %}progress-bar-danger{% elif health_status.disk_percent > 75 %}progress-bar-warning{% else %}progress-bar-success{% endif %}" 
                         style="width: {{ health_status.disk_percent|default:0 }}%"></div>
                </div>
                <div class="metric-item mt-3">
                    <span class="metric-label">已用空间</span>
                    <span class="metric-value">{{ health_status.disk_used|default:0 }} GB</span>
                </div>
                <div class="metric-item">
                    <span class="metric-label">总空间</span>
                    <span class="metric-value">{{ health_status.disk_total|default:0 }} GB</span>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 系统统计和存储信息 -->
    <div class="row">
        <div class="col-md-4">
            <div class="system-card">
                <h5 class="mb-3">系统统计</h5>
                <div class="metric-item">
                    <span class="metric-label">操作系统</span>
                    <span class="metric-value">{{ system_stats.platform|truncatechars:20 }}</span>
                </div>
                <div class="metric-item">
                    <span class="metric-label">Python版本</span>
                    <span class="metric-value">{{ system_stats.python_version }}</span>
                </div>
                <div class="metric-item">
                    <span class="metric-label">Django版本</span>
                    <span class="metric-value">{{ system_stats.django_version }}</span>
                </div>
                <div class="metric-item">
                    <span class="metric-label">总用户数</span>
                    <span class="metric-value">{{ system_stats.total_users }}</span>
                </div>
                <div class="metric-item">
                    <span class="metric-label">总资产数</span>
                    <span class="metric-value">{{ system_stats.total_assets }}</span>
                </div>
                <div class="metric-item">
                    <span class="metric-label">今日操作</span>
                    <span class="metric-value">{{ system_stats.today_operations }}</span>
                </div>
                <div class="metric-item">
                    <span class="metric-label">本周操作</span>
                    <span class="metric-value">{{ system_stats.week_operations }}</span>
                </div>
                <div class="metric-item">
                    <span class="metric-label">今日错误</span>
                    <span class="metric-value text-{% if system_stats.error_logs_today > 0 %}danger{% else %}success{% endif %}">
                        {{ system_stats.error_logs_today }}
                    </span>
                </div>
            </div>
        </div>
        
        <div class="col-md-4">
            <div class="system-card">
                <h5 class="mb-3">存储使用情况</h5>
                <div class="storage-chart">
                    <canvas id="storageChart"></canvas>
                </div>
                <div class="mt-3">
                    <div class="metric-item">
                        <span class="metric-label">媒体文件</span>
                        <span class="metric-value">{{ storage_info.media_size_mb }} MB</span>
                    </div>
                    <div class="metric-item">
                        <span class="metric-label">静态文件</span>
                        <span class="metric-value">{{ storage_info.static_size_mb }} MB</span>
                    </div>
                    <div class="metric-item">
                        <span class="metric-label">日志文件</span>
                        <span class="metric-value">{{ storage_info.log_size_mb }} MB</span>
                    </div>
                    <div class="metric-item">
                        <span class="metric-label">总计</span>
                        <span class="metric-value">{{ storage_info.total_size_mb }} MB</span>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="col-md-4">
            <div class="system-card">
                <h5 class="mb-3">快速操作</h5>
                <button class="btn btn-outline-primary quick-action-btn" onclick="clearCache()">
                    <i class="fas fa-broom"></i> 清理缓存
                </button>
                <button class="btn btn-outline-warning quick-action-btn" onclick="cleanupLogs()">
                    <i class="fas fa-trash-alt"></i> 清理日志
                </button>
                <button class="btn btn-outline-info quick-action-btn" onclick="optimizeDatabase()">
                    <i class="fas fa-database"></i> 优化数据库
                </button>
                <button class="btn btn-outline-success quick-action-btn" onclick="backupSystem()">
                    <i class="fas fa-download"></i> 备份系统
                </button>
                <button class="btn btn-outline-secondary quick-action-btn" onclick="runHealthCheck()">
                    <i class="fas fa-stethoscope"></i> 健康检查
                </button>
            </div>
        </div>
    </div>
    
    <!-- 数据库统计和最近日志 -->
    <div class="row">
        <div class="col-md-6">
            <div class="system-card">
                <h5 class="mb-3">数据库统计</h5>
                <div class="metric-item">
                    <span class="metric-label">数据库大小</span>
                    <span class="metric-value">{{ database_stats.db_size_mb|default:0 }} MB</span>
                </div>
                
                {% if database_stats.table_stats %}
                <div class="database-table mt-3">
                    <table class="table table-sm">
                        <thead>
                            <tr>
                                <th>表名</th>
                                <th>记录数</th>
                                <th>大小(MB)</th>
                            </tr>
                        </thead>
                        <tbody>
                            {% for table in database_stats.table_stats %}
                            <tr>
                                <td>{{ table.table_name }}</td>
                                <td>{{ table.row_count|default:0 }}</td>
                                <td>{{ table.size_mb|default:0 }}</td>
                            </tr>
                            {% endfor %}
                        </tbody>
                    </table>
                </div>
                {% endif %}
                
                {% if database_stats.error %}
                <div class="text-muted text-center py-3">
                    <i class="fas fa-exclamation-triangle"></i>
                    无法获取数据库统计信息
                </div>
                {% endif %}
            </div>
        </div>
        
        <div class="col-md-6">
            <div class="system-card">
                <h5 class="mb-3">最近系统日志</h5>
                <div style="max-height: 400px; overflow-y: auto;">
                    {% for log in recent_logs %}
                    <div class="log-item {{ log.level|lower }}">
                        <div class="d-flex justify-content-between align-items-start">
                            <div>
                                <strong>{{ log.action }}</strong>
                                <p class="mb-1">{{ log.message|truncatechars:100 }}</p>
                                <small class="text-muted">
                                    {% if log.user %}{{ log.user.username }}{% else %}系统{% endif %} - 
                                    {{ log.created_at|date:"m-d H:i" }}
                                </small>
                            </div>
                            <span class="badge bg-{% if log.level == 'ERROR' %}danger{% elif log.level == 'WARNING' %}warning{% else %}info{% endif %}">
                                {{ log.level }}
                            </span>
                        </div>
                    </div>
                    {% empty %}
                    <div class="text-center text-muted py-4">
                        <i class="fas fa-file-alt fa-2x mb-2"></i>
                        <p>暂无系统日志</p>
                    </div>
                    {% endfor %}
                </div>
                
                <div class="text-center mt-3">
                    <a href="{% url 'assets:system_log_list' %}" class="btn btn-outline-primary btn-sm">
                        查看所有日志
                    </a>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script src="https://cdn.jsdelivr.net/npm/chart.js@3.9.1/dist/chart.min.js"></script>
<script>
// 存储使用情况图表
document.addEventListener('DOMContentLoaded', function() {
    const ctx = document.getElementById('storageChart').getContext('2d');
    new Chart(ctx, {
        type: 'doughnut',
        data: {
            labels: ['媒体文件', '静态文件', '日志文件'],
            datasets: [{
                data: [
                    {{ storage_info.media_size_mb|default:0 }},
                    {{ storage_info.static_size_mb|default:0 }},
                    {{ storage_info.log_size_mb|default:0 }}
                ],
                backgroundColor: [
                    '#667eea',
                    '#764ba2',
                    '#f093fb'
                ],
                borderWidth: 0
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    position: 'bottom',
                    labels: {
                        padding: 20,
                        usePointStyle: true
                    }
                }
            }
        }
    });
});

// 刷新仪表板
function refreshDashboard() {
    const indicator = document.getElementById('refreshIndicator');
    indicator.style.display = 'inline-block';
    
    // 模拟刷新延迟
    setTimeout(() => {
        window.location.reload();
    }, 1000);
}

// 查看性能监控
function viewPerformanceMonitor() {
    window.location.href = '{% url "assets:system_performance_monitor" %}';
}

// 查看系统维护
function viewSystemMaintenance() {
    window.location.href = '{% url "assets:system_maintenance" %}';
}

// 快速操作函数
function clearCache() {
    if (confirm('确定要清理系统缓存吗？')) {
        performMaintenanceAction('clear_cache');
    }
}

function cleanupLogs() {
    const days = prompt('请输入要保留的天数（默认30天）:', '30');
    if (days && !isNaN(days)) {
        performMaintenanceAction('cleanup_logs', {days: days});
    }
}

function optimizeDatabase() {
    if (confirm('确定要优化数据库吗？此操作可能需要一些时间。')) {
        performMaintenanceAction('optimize_database');
    }
}

function backupSystem() {
    if (confirm('确定要备份系统数据吗？')) {
        performMaintenanceAction('backup_system');
    }
}

function runHealthCheck() {
    performMaintenanceAction('check_health');
}

// 执行维护操作
function performMaintenanceAction(action, params = {}) {
    const formData = new FormData();
    formData.append('action', action);
    formData.append('csrfmiddlewaretoken', '{{ csrf_token }}');
    
    // 添加额外参数
    for (const [key, value] of Object.entries(params)) {
        formData.append(key, value);
    }
    
    fetch('{% url "assets:system_maintenance" %}', {
        method: 'POST',
        body: formData
    })
    .then(response => response.text())
    .then(data => {
        // 显示成功消息
        showAlert('success', '操作已提交，正在处理...');
        
        // 延迟刷新页面
        setTimeout(() => {
            window.location.reload();
        }, 2000);
    })
    .catch(error => {
        console.error('Error:', error);
        showAlert('error', '操作失败，请重试');
    });
}

// 显示提示信息
function showAlert(type, message) {
    const alertDiv = document.createElement('div');
    alertDiv.className = `alert alert-${type} alert-dismissible fade show position-fixed`;
    alertDiv.style.cssText = 'top: 20px; right: 20px; z-index: 9999; min-width: 300px;';
    alertDiv.innerHTML = `
        ${message}
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    `;
    
    document.body.appendChild(alertDiv);
    
    // 3秒后自动消失
    setTimeout(() => {
        if (alertDiv.parentNode) {
            alertDiv.parentNode.removeChild(alertDiv);
        }
    }, 3000);
}

// 自动刷新系统状态（每60秒）
setInterval(() => {
    fetch('/assets/system/ajax-system-status/', {
        method: 'POST',
        headers: {
            'X-CSRFToken': '{{ csrf_token }}',
            'Content-Type': 'application/json'
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            // 更新页面上的关键指标
            updateSystemMetrics(data.data);
        }
    })
    .catch(error => {
        console.error('Failed to update system status:', error);
    });
}, 60000);

// 更新系统指标
function updateSystemMetrics(data) {
    // 更新CPU使用率
    const cpuElement = document.querySelector('.metric-value');
    if (cpuElement && data.cpu_percent !== undefined) {
        cpuElement.textContent = data.cpu_percent + '%';
    }
    
    // 更新进度条
    const progressBars = document.querySelectorAll('.progress-bar-custom');
    if (progressBars.length >= 3) {
        progressBars[0].style.width = (data.cpu_percent || 0) + '%';
        progressBars[1].style.width = (data.memory_percent || 0) + '%';
        progressBars[2].style.width = (data.disk_percent || 0) + '%';
    }
}
</script>
{% endblock %}